package com.wanji.sdk.impl.websocket;

import com.wanji.protocol.api.ByteBufEncoder;
import com.wanji.protocol.api.DeviceMessageDecoder;
import com.wanji.protocol.api.ProtocolTemplate;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class WebSocketProtocol extends ProtocolTemplate {
    @Override
    protected DeviceMessageDecoder<?> createDecoder() {
        return new WebSocketDecoder();
    }

    @Override
    protected ByteBufEncoder<?> createEncoder() {
        return new WebSocketEncoder();
    }

    @Override
    protected void initPipeline(ChannelPipeline pipeline) {
        pipeline.addLast(
                // HTTP编解码器
                new HttpServerCodec(),
                // HTTP消息聚合器
                new HttpObjectAggregator(65536),
                // 支持异步发送大的码流
                new ChunkedWriteHandler(),
                // WebSocket协议处理器
                new WebSocketServerProtocolHandler("/ws", null, true));
    }

    @Override
    public String protocolType() {
        return "WEBSOCKET";
    }
}
